package controllers

import (
	"cronjob/libs"
	"cronjob/models"
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego"

	_ "github.com/astaxie/beego"
)

type LoginController struct {
	BaseController
}

func (this *LoginController) Login() {
	this.Data["siteName"] = "任务管理系统"
	this.TplName = this.controllerName + "/login.html"
}

func (this *LoginController) LoginIn() {
	username := strings.TrimSpace(this.GetString("username"))

	password := strings.TrimSpace(this.GetString("password"))

	//this.Ctx.WriteString(username + "==" + password)

	if username != "" && password != "" {
		//根据用户查询，信息
		adminInfo, err := models.AdminGetByName(username)

		// this.Ctx.WriteString(libs.MD5([]byte(password + adminInfo.Salt)))

		if err != nil || adminInfo.Password != libs.MD5([]byte(password+adminInfo.Salt)) {
			this.ajaxMsg("账号和密码不正确", MSG_ERR)
		} else if adminInfo.Status == 0 {
			this.ajaxMsg("该账号被禁", MSG_ERR)
		} else {

			this.userID = adminInfo.Id
			this.user = adminInfo

			// 修改最后登录时间，和ip
			adminInfo.LastLogin = time.Now().Unix()
			adminInfo.LastIp = this.getClientIP()

			adminInfo.Update("LastLogin", "LastIp")

			// 登录ip加密码盐
			authkey := libs.MD5([]byte(adminInfo.LastIp + "|" + adminInfo.Salt))
			this.Ctx.SetCookie("auth", strconv.Itoa(this.userID)+"|"+authkey, 60*60*24*7)

			this.ajaxMsg("登录成功", MSG_OK)
		}
	}

}

// 退出登录  LoginOut

func (this *LoginController) LoginOut() {
	this.Ctx.SetCookie("auth", "", -1)
	this.Redirect(beego.URLFor("LoginController.Login"), 302)
}
